<template>
  <view v-if="loading">
    <BlogForComment :post="postInfo" :channel="channelInfo"/>
    <!--    按类型查看评论-->
    <view v-if="!showEmptyComent" @click="openPopup"
          style="display: flex;align-items: center;margin: 15px  15px 0 15px">
      <up-text bold size="14" color="black" suffixIcon="arrow-down"
               iconStyle="font-weight:bolder;font-size: 16px;padding-left: 5px;color:black"
               :text="commentType[commentIndex].name"></up-text>
    </view>
    <!--    空评论页面-->
    <view v-if="showEmptyComent" class="empty-comment">
      <image src="https://www.douluodalu.icu:9000/school/static/empty.png" style="width: 20vh;height: 20vh;">
      </image>
      <text>做ta的第一个暖场嘉宾</text>
      <!--评论页面-->
    </view>
    <view v-if="showEmptyOwner" class="empty-comment">
      <u-empty
          mode="comment"
          text="暂无楼主回复"
          icon="http://cdn.uviewui.com/uview/empty/comment.png"
      >
      </u-empty>
    </view>
    <view v-if="!showEmptyOwner && !showEmptyComent"
          @tap="toAllReply(res)" class="comment"
          @longtap.stop="handleRemove(res, index)"
          v-for="(res, index) in commentList" :key="res.id">
      <view class="left">
        <image @tap.stop="toUserInfo(res.userId)" class="avatar"
               :src="res.avatar" lazy-load mode="aspectFill"></image>
      </view>
      <view class="right">
        <view class="top">
          <view @tap.stop="toUserInfo(res.userId)" class="name">{{ res.username }}</view>
          <view class="like" :class="{ highlight: res.isLiked }">
            <view class="num">{{ res.liked }}&nbsp;</view>
            <image v-if="!res.isLiked" class="like-image" src="https://www.douluodalu.icu:9000/school/static/like.png"
                   @tap.stop="getLike(index)"></image>
            <image v-if="res.isLiked" class="like-image" src="https://www.douluodalu.icu:9000/school/static/like_active.png"
                   @tap.stop="getLike(index)"></image>
          </view>
        </view>
        <view class="content">{{ res.content }}</view>
        <u-grid :border="false">
          <u-grid-item v-for="(item,fileIndex) in res.fileList"
                       :key="fileIndex"
                       @tap.stop="sendFileList(fileIndex,index)">
            <navigator url="/pages/index/fullScreen" animation-type="">

              <image v-if="isImageUrl(item)"
                     class="file-item-multi"
                     lazy-load
                     :src="item">
                <template v-slot:loading>
                  <up-loading-icon></up-loading-icon>
                </template>
                <template #error>
                  <view style="font-size: 24rpx;">加载失败</view>
                </template>
              </image>
              <video v-if="isVideoUrl(item)"
                     object-fit="cover"
                     style="position: relative;"
                     :enable-progress-gesture="false"
                     :vslide-gesture-in-fullscreen="false"
                     :show-fullscreen-btn="false"
                     :show-center-play-btn="false"
                     :show-play-btn="false"
                     class="file-item-multi" :src="item.fileList">
                <cover-image
                    class="play-btn"
                    src="https://www.douluodalu.icu:9000/school/static/play_white.png">
                </cover-image>
              </video>
            </navigator>

          </u-grid-item>
        </u-grid>

        <view class="reply-box" v-if="res.child != undefined">
          <view class="item">
            <view class="username">{{ res.child[0].username }}
              &nbsp;<text v-if="res.child[0].userId == postInfo.authorId" class="owner">楼主</text>
              :&nbsp;
            </view>
            <view class="text">
              <text style="color: #4ea4f9" v-if="res.child[0].images != '' &&  res.child[0].videos == ''">[图片]</text>
<!--              <text style="color: #4ea4f9" v-if="res.child[0].images == '' &&  res.child[0].videos != ''">[视频]</text>-->
<!--              <text style="color: #4ea4f9" v-if="res.child[0].images != '' &&  res.child[0].videos != ''">[视频]</text>-->
              <text v-else>{{ res.child[0].content }}</text>
            </view>
          </view>
          <view class="item" v-if="res.child != undefined && res.child.length > 1">
            <view class="username">{{ res.child[1].username }}
              &nbsp;<text v-if="res.child[1].userId == postInfo.authorId" class="owner">楼主</text>
              :&nbsp;
            </view>
            <view class="text">{{ res.child[1].content }}</view>
          </view>
          <view class="all-reply" v-if="res.child != undefined && res.child.length > 2">
            查看{{ res.child.length }}条评论
          </view>
        </view>
        <view class="bottom">
          {{ formatTimeAgo(res.publishTime) }}
          {{ formatLocation(res.location) }}
          <view @tap.stop="reply(res,index)" class="reply">回复</view>
        </view>
      </view>
    </view>
    <u-action-sheet cancelText="取消" @close="closeRemoveAction"
                    @select="selectClick"
                    :closeOnClickOverlay="true"
                    :actions="removeActionList"
                    :round="10"
                    :show="showRemove"></u-action-sheet>
  </view>
  <PostDetailSkeleton v-else></PostDetailSkeleton>
  <!--    底部评论输入框-->
  <scroll-view scroll-y style="height: calc(50vh - env(safe-area-inset-bottom))">
    <view>
      <view id="bottom-list" :style="{bottom: keyboardHeight + 'px'}">
        <scroll-view v-if="fileList1" :scroll-x="true" scroll-with-animation>
          <view class="bottom-media-list">
            <view v-for="(item, index) in fileList1"
                  @tap.stop="sendFileList2(index)"
                  style="position: relative"
                  class="bottom-media-list-item" :key="index">
              <navigator url="/pages/index/fileFullScreen">
                <image v-if="isImageUrl(item)"
                       class="bottom-media-list-item-image"
                       :src="item">

                </image>

                <video
                    v-else
                    :enable-progress-gesture="false"
                    :vslide-gesture-in-fullscreen="false"
                    :show-fullscreen-btn="false"
                    :show-center-play-btn="false"
                    :show-play-btn="false"
                    class="bottom-media-list-item-image" :src="item">+
                </video>
                <view @tap.stop="deletePic(index)" class="close-images">
                  <u-icon color="#fa4358"
                          name="close-circle-fill">
                  </u-icon>
                </view>

              </navigator>
            </view>
          </view>
        </scroll-view>
        <view class="textarea-model-wrapper">
            <textarea
                v-model="comment.content"
                fixed
                :focus="textareaFocus"
                style="width: 60vw"
                :show-confirm-bar="false"
                :adjust-position="false"
                :placeholder="textareaPlaceholder"
                @focus="getKeyboardHeight"
                @blur="removeKeyboardHeight"
                @input="onTextareaInput"
                maxlength="-1"
                auto-height
            ></textarea>
          <image @click="getMedia(item.type)"
                 class="media"
                 :src="item.url"
                 border="none"
                 :key="item.type" v-for="(item,index) in bottomList2">
          </image>
          <button :disabled="comment.content.trim() == '' && !fileList1.length > 0"
                  style="border: none"
                  type="default"
                  class="send-btn" @click="sendComment">发送
          </button>
        </view>
      </view>
    </view>
  </scroll-view>

  <!--  底部评论类型弹出层-->
  <u-popup :round="10" :show="show" mode="bottom" @close="close" @open="open">
    <view style="color: black;display: flex;justify-content: center;padding: 5px">
      <text>评论排序</text>
    </view>
    <view style="border-bottom: 1px solid rgba(138,138,138,0.05);padding: 5px"
          v-for="(item,index) in commentType"
          :key="item.type" @click="notifyChoose(index)">
      <view style="display: flex;align-items: center;justify-content: space-between">
        <view style="display: flex;align-items: center;">
          <image :src="item.url" lazy-load style="width: 15px;height: 15px;padding: 15px 10px" @click="close"></image>
          <text style="color: black;font-size: 15px;font-weight: 530">{{ item.name }}</text>
        </view>
        <image src="https://www.douluodalu.icu:9000/school/static/gou.png" style="height: 22px;width: 22px;margin-right: 10px"
               v-show="commentIndex === index"></image>
      </view>
    </view>
    <view @click="show=false" style="height: 50px;display: flex;align-items: center;
    justify-content: center;border: none;outline: none;font-weight: bold;font-size: 16px;
    background-color: rgba(138,138,138,0.05);color: rgba(0,0,0,0.5);">
      关闭
    </view>
  </u-popup>


</template>

<script>
import BlogForComment from "@/components/BlogForComment.vue";
import {getPostById, postArticle} from "@/api/article";
import {getChannelById} from "@/api/channel";
import PostDetailSkeleton from "@/components/skeleton/PostDetailSkeleton.vue";
import {addComment, getCommentList, likeComment, removeCommentById} from "@/api/comment";
import index2 from "@/components/topic/index2.vue";
import replyComponent from "@/components/comment/replyComponent.vue";
import {getToken, getUserId} from "@/utils/auth";
import authorize from "@/utils/authorize";
import {collectPost} from "@/api/post";

export default {
  components: {index2, PostDetailSkeleton, BlogForComment, replyComponent},
  data() {
    return {
      // 底部媒体列表
      showSkeleton: false,
      removing: false,
      showRemove: false,
      removeItem:{},
      removeActionList: [{
        name:'删除',
      }],
      topicInfo: '',
      showTopicPopup: false,
      closeTopicTag: true,
      tempFilePaths: [],
      fileList1: [],
      textareaPlaceholder: '请输入内容',
      focusShow: false,
      textareaWidth: 65,
      textareaFocus: false,
      showEmptyComent: false,
      showEmptyOwner: false,
      maxHeight: '20px',
      maxLines: 4,
      showReplyPopup: false,
      //键盘高度
      keyboardHeight: 0,
      keyboardHeight1: 0,
      bottomList: [
        {
          url: 'https://www.douluodalu.icu:9000/school/static/post_image.png',
          type: 1
        },
        {
          url: 'https://www.douluodalu.icu:9000/school/static/post_collection.png',
          type: 6
        }
      ],
      bottomList2: [{
        url: 'https://www.douluodalu.icu:9000/school/static/post_image.png',
        type: 1
      }, {
        url: 'https://www.douluodalu.icu:9000/school/static/post_collection.png',
        type: 6
      }
      ],
      // 聊天框距离底部的高度
      bottomHeight: 0,
      childCommentIndex: null,
      childCommentInfo: [],
      comment: {
        content: '', // 内容
        images: [], // 图片
        videos: [], // 视频
        parentId: '',
        postId: '',
        rootCommentId: '',
      },
      show: false,
      loading: false,
      commentIndex: 0,
      current: 0,
      commentType: [
        { type: 1, name: "最热评论", url: "https://www.douluodalu.icu:9000/school/static/hot-comment.png" },
        {type: 2, name: '最新评论', url: 'https://www.douluodalu.icu:9000/school/static/new-comment.png'},
        {type: 3, name: '只看楼主', url: 'https://www.douluodalu.icu:9000/school/static/only-comment.png'},
        // {type: 4, name: '有视频', url: 'http://www.douluodalu.icu:9000/school/static/video-comment.png'}
      ],
      channelInfo: {},
      commentList: [],
      postInfo: {},
      searchParamsMap: [
        {
          hot: true,
          latest: false,
          onlyOwner: false,
          haveVideo: false,
          pageSize: 15,
          current: 1,
          postId: ''
        }, {
          hot: false,
          latest: true,
          onlyOwner: false,
          haveVideo: false,
          pageSize: 15,
          current: 1,
          postId: ''
        }, {
          hot: false,
          latest: false,
          onlyOwner: true,
          haveVideo: false,
          pageSize: 15,
          current: 1,
          postId: ''
        }, {
          hot: false,
          latest: false,
          onlyOwner: false,
          haveVideo: true,
          pageSize: 15,
          current: 1,
          postId: ''
        },
      ],
      searchParams: {
        hot: true,
        latest: false,
        onlyOwner: false,
        haveVideo: false,
        pageSize: 15,
        current: 1,
        postId: ''
      },
    };
  },
  onLoad(options) {
    this.getPostInfo(options.id);
  },
  onUnload() {
    uni.offKeyboardHeightChange()//如果不传入监听的对象，则移除所有监听函数
    // uni.$off('newPost')

  },
  methods: {

    handleRemove(item,index){
      this.removing = true
      let userId = getUserId();
      if ( item.userId == userId) {
        this.showRemove = true
        this.removeItem.item = item
        this.removeItem.index = index
        this.removeItem.ancestorId = 0
      }
    },
    async selectClick(index){
      if(index?.name === '删除'){
        let _this = this
        uni.showModal({
          title: '提示',
          content: '内容删除后无法找回，是否确认删除？',
          success: async  (res) => {
            if (res.confirm) {
              const response = await removeCommentById(_this.removeItem.item.id,_this.removeItem.ancestorId)
              if (response.code == 200 && response?.data == true) {
                this.commentList.splice(this.removeItem.index, 1)
                uni.showToast({
                  title: '删除成功',
                  icon: 'none'
                });
              } else {
                uni.showToast({
                  title: response?.data === undefined ? '删除失败' : response?.data,
                  icon: 'none'
                });
              }
              _this.showRemove = false

            } else if (res.cancel) {
              console.log('用户点击取消');
            }
          }
        });
      }
      this.removing = false
    },
    closeRemoveAction(){
      // this.removeItem = {}
      this.showRemove = false
      this.removing = false

    },
    deletePic(index) {
      if(this.fileList1?.length > 0){
        this.fileList1.splice(index, 1)
      }
    },
    toUserInfo(userId){
      uni.navigateTo({
        url: '/pages/my/userInfo?id=' + userId
      })
    },
    sendFileList(fileIndex, commentIndex) {
      setTimeout(() => {
        let comment = this.commentList[commentIndex]
        comment.title = comment.content
        uni.$emit('sendFileList', {
          post: this.commentList[commentIndex],
          fileList: comment.fileList,
          currentIndex: fileIndex
        })
      }, 500)

    },
    sendFileList2(currentIndex) {
      setTimeout(() => {
        uni.$emit('sendFileList', {
          fileList: this.fileList1,
          currentIndex: currentIndex
        })
      }, 500)

    },

    isImageUrl(url) {
      const dotIndex = url.lastIndexOf(".");
      // 截取路径的扩展名
      const extension = url.substring(dotIndex);
      // 判断扩展名是否是图片扩展名
      const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tif', '.tiff'];
      // console.log(url+'----后缀：'+ extension +'----->  '+imageExtensions.includes(extension))
      return imageExtensions.includes(extension);
    },
    // 新增图片
    uploadFile(tempFilePaths) {
      uni.uploadFile({
        url: this.$BASE_UPLOAD, //仅为示例，非真实的接口地址
        filePath: tempFilePaths,
        // filePath: tempFilePaths[i],
        name: 'file',
        header: {
          'Authorization': getToken(),
        },
        success: (uploadFileRes) => {
          let res = (JSON.parse(uploadFileRes.data)).data.url
          this.fileList1.push(res)
          this.textareaFocus = true
        }
      })
    },
    isVideoUrl(url) {
      const dotIndex = url.lastIndexOf(".");
      // 截取路径的扩展名
      const extension = url.substring(dotIndex);
      // 判断扩展名是否是图片扩展名
      let videoExtensions = [".3gp", ".avi", ".flv", ".mkv", ".mov", ".mpg", ".mp4", ".rmvb", ".wmv"];
      // console.log(url+'----后缀：'+ extension +'----->  '+imageExtensions.includes(extension))
      return videoExtensions.includes(extension) && url.startsWith("http");
    },
    getMedia(type) {
      let _this = this
      if (type === 1 || type === 2) {
        if (this.fileList1.length >= 9) {
          uni.showToast({
            title: '最多上传9张图片哦',
            icon: 'none',
            duration: 2000
          })
          return
        }
        this.$authorize('camera', false, true).then(() => {
          //成功授权后相应逻辑
          if (type === 1) {
            uni.chooseMedia({
              count: 9 - this.fileList1.length,
              mediaType: ['image'],
              //可以指定是原图还是压缩图，默认二者都有
              sourceType: ['camera', 'album'], //从相册选择
              success: res => {
                res.tempFiles.forEach(item => {
                  _this.uploadFile(item.tempFilePath)
                })
                if (_this.fileList1.length > 9) {
                  _this.fileList1.splice(9, _this.fileList1.length - 9);
                  uni.showToast({
                    title: '最多选择九个哦',
                    icon: 'none',
                    duration: 2000
                  })
                }
              }
            });
          }
          if (type === 2) {
            uni.chooseMedia({
              count: 9 - this.fileList1.length,
              mediaType: ['video'],
              sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
              sourceType: ['camera', 'album'], //从相册选择
              success: function (res) {
                res.tempFiles.forEach(item => {
                  _this.uploadFile(item.tempFilePath)
                })
                if (_this.fileList1.length > 9) {
                  _this.fileList1.splice(9, _this.fileList1.length - 9);
                  uni.showToast({
                    title: '最多选择九个哦',
                    icon: 'none',
                    duration: 2000
                  })
                }
              }
            });
          }
        }).catch(() => {
          uni.showToast({title: '请先授权相机权限'})
        }).finally(() => {
          //无论授权成功或者失败都执行的逻辑
        });
      }
      if (type === 3) {
        authorize('record', false, true).then(() => {
          this.keyboardHeight = this.keyboardHeight1;
          //成功授权后相应逻辑
        }).catch(() => {
          //拒绝授权后相应逻辑
          uni.showToast({title: '请先授权麦克风权限'})
        }).finally(() => {
          //无论授权成功或者失败都执行的逻辑
        });
      }
      if (type === 4) {
        this.recordClose()
        this.keyboardHeight = this.keyboardHeight1;
        uni.showToast({title: '表情功能正在开发中'})
      }
      if (type === 5) {
        uni.showToast({title: '@功能正在开发中'})
      }
      if (type === 6) {
        this.collectPost()
      }
    },
    async sendComment() {
      let token = getToken();
      if (!(token !== null && token !== '' && token !== undefined)) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateTo({url: '/pages/my/login'})
        }, 500)
        return;
      }
      if ((this.comment.content.trim() == '' && !this.fileList1) || (this.comment.content.trim().length == 0 && !this.fileList1)) {
        uni.showToast({
          title: '你还没有输入评论',
          icon: 'none'
        })
        return
      }
      if (this.fileList1?.length > 0) {
        this.comment.images = []
        this.comment.videos = []
        this.fileList1.forEach(item => {
          if (this.isImageUrl(item)) {
            this.comment.images.push(item)
          } else {
            this.comment.videos.push(item)
          }
        })
      }
      if (this.comment.images?.length > 0) {
        this.comment.images = this.comment.images.join(',')
      } else {
        this.comment.images = null
      }
      if (this.comment.videos?.length > 0) {
        this.comment.videos = this.comment.videos.join(',')
      } else {
        this.comment.videos = null
      }

      this.comment.postId = this.postInfo.id
      console.log(this.comment)
      const res = await addComment(this.comment)

      this.tempFilePaths = []
      this.fileList1 = []
      this.tempFilePath = ''
      this.comment.content = ''
      this.comment.videos = []
      this.comment.images = []
      this.comment.parentId = ''
      this.comment.rootCommentId = ''
      this.comment.postId = ''
      if(res.code == 200 && res.data?.id !== undefined){
        if (this.showEmptyComent && res.data.parentId == null) {
          res.data.fileList = []
          if (res.data.images != undefined && res.data.images != null) {
            let imagesList = res.data.images.split(',');
            res.data.fileList = [...res.data.fileList, ...imagesList]
          }
          if (res.data.videos != undefined && res.data.videos != null) {
            let videosList = res.data.videos.split(',');
            res.data.fileList = [...res.data.fileList, ...videosList]
          }
          this.commentList = new Array(res.data)
        }
        if (!this.showEmptyComent && res.data.parentId == null) {
          res.data.fileList = []
          if (res.data.images != undefined && res.data.images != null) {
            let imagesList = res.data.images.split(',');
            res.data.fileList = [...res.data.fileList, ...imagesList]
          }
          if (res.data.videos != undefined && res.data.videos != null) {
            let videosList = res.data.videos.split(',');
            res.data.fileList = [...res.data.fileList, ...videosList]
          }
          this.commentList = [res.data, ...this.commentList]
        }
        if (this.childCommentIndex != null) {
          res.data.fileList = []
          if (res.data.images != undefined && res.data.images != null) {
            let imagesList = res.data.images.split(',');
            res.data.fileList = [...res.data.fileList, ...imagesList]
          }
          if (res.data.videos != undefined && res.data.videos != null) {
            let videosList = res.data.videos.split(',');
            res.data.fileList = [...res.data.fileList, ...videosList]
          }
          let newChildComment = this.commentList[this.childCommentIndex]
          newChildComment.child = [res.data, ...newChildComment.child]
          this.childCommentIndex = null
        }
        this.showEmptyComent = false
        this.showEmptyOwner = false
        // this.getComment()
      }else {
        uni.showToast({
          title: res.data,
          icon: 'none',
          duration: 2000
        })
      }

      this.loading = true
    },
    reply(comment, index) {

      let replyTo = comment.username
      let parent = comment.id
      this.textareaPlaceholder = `回复 ${replyTo} :`
      this.textareaFocus = true
      this.comment.parentId = parent
      this.comment.rootCommentId = parent
      if (comment.child != undefined) {
        this.childCommentIndex = index
      }
    },
    async getComment() {
      this.searchParams.postId = this.postInfo.id
      const {data: res} = await getCommentList(this.searchParams)

      if ((res.data == null || res.data == undefined) && this.commentIndex != 2) {
        this.showEmptyComent = true
        this.showEmptyComent = false
      }else if((res.data == null || res.data == undefined) && this.commentIndex == 2){
        this.showEmptyComent = false
        this.showEmptyOwner = true
      }else{
        this.showEmptyComent = false
        this.showEmptyOwner = false
        res.data.forEach(item => {
          item.fileList = []
          if (item?.images != undefined && item.images != null) {
            let imagesList = item.images.split(',');
            item.fileList = [...item.fileList, ...imagesList]
          }
          if (item?.videos != undefined && item.videos != null) {
            let videosList = item.videos.split(',');
            item.fileList = [...item.fileList, ...videosList]
          }
        })
        this.commentList = res.data;
      }
    },
    onTextareaInput() {
      // 在这里可以处理行数
    },
    getKeyboardHeight(event) {
      this.keyboardHeight = event.detail.height
      if (this.keyboardHeight < 0) this.keyboardHeight = 0;
      this.focusShow = true
      this.textareaWidth = 75
    },
    removeKeyboardHeight(event) {
      // 在这里可以处理键盘高度
      this.textareaPlaceholder = '请输入内容'
      this.textareaFocus = false
      this.keyboardHeight = 0
      if (this.keyboardHeight < 0) this.keyboardHeight = 0;
      if (this.fileList1.length > 0) {
        this.focusShow = true
      } else {
        this.focusShow = false
      }
      this.textareaWidth = 65
    },
    notifyChoose(index) {
      console.log(index)
      this.commentIndex = index
      this.searchParams = this.searchParamsMap[index]
      this.getComment()
      this.show = false
    },
    openPopup(popupData) {
      this.popupData = popupData
      uni.$u.sleep().then(() => {
        this.show = !this.show
      })
    },
    open() {
    },
    close() {
      this.show = false
    },
    open2() {
      // console.log('open');
    },
    close2() {
      this.showReplyPopup = false
      // console.log('close');
    },
    formatTimeAgo(originalTimestamp) {
      const now = new Date();
      const timestampPlus8Hours = new Date(originalTimestamp);
      timestampPlus8Hours.setHours(timestampPlus8Hours.getHours() + 8);

      const timeDifference = now - timestampPlus8Hours;
      const seconds = Math.floor(timeDifference / 1000);
      const minutes = Math.floor(seconds / 60);
      const hours = Math.floor(minutes / 60);
      const days = Math.floor(hours / 24);
      const padZero = (num) => (num < 10 ? `0${num}` : num);

      if (days < 365) {
        if (days == 0) {
          if (hours >= 12) {
            return `${padZero(timestampPlus8Hours.getUTCMonth() + 1)}/${padZero(timestampPlus8Hours.getUTCDate())}`;
          } else if (hours > 0 && hours <= 12) {
            return `${hours}小时前`;
          } else if (minutes >= 1) {
            return `${minutes}分钟前`;
          } else {
            return '刚刚';
          }
        } else if (days == 1) {
          return `昨天 ${timestampPlus8Hours.getHours()}:${('0' + timestampPlus8Hours.getMinutes()).slice(-2)}`;
        } else {
          return `${padZero(timestampPlus8Hours.getUTCMonth() + 1)}/${padZero(timestampPlus8Hours.getUTCDate())}`;
        }
      } else {
        return `${timestampPlus8Hours.getUTCFullYear()}/${padZero(timestampPlus8Hours.getUTCMonth() + 1)}/${padZero(timestampPlus8Hours.getUTCDate())}`;
      }
    },
    formatLocation(location) {
      if (location == null) {
        return '未知';
      }
      location = location.replace(/省|市/g, '');

      return location;
    },
    async getPostInfo(id) {
      const {data: res} = await getPostById(id)

      if (res.code == 200) {
        this.postInfo = res.data
        // console.log(res.data.publishTime)
        this.postInfo.publishTime = this.formatTimeAgo(res.data.publishTime)
        this.postInfo.location = this.formatLocation(res.data.location)
        console.log(this.postInfo.isCollected)
        if (this.postInfo.isCollected === true && this.postInfo?.isCollected !== undefined) {
          this.bottomList2 = [
            {
              url: 'https://www.douluodalu.icu:9000/school/static/post_image.png',
              type: 1
            }, {
              url: 'https://www.douluodalu.icu:9000/school/static/post_collection_active.png',
              type: 6
            }
          ]
        }
        await this.getChannelInfo(this.postInfo.channelId)
        await this.getComment();
        this.loading = true
      } else {
        uni.showModal({
          title: '提示',
          content: '获取文章失败',
          showCancel: false
        });
      }

    },
    async getChannelInfo(id) {
      const res = await getChannelById(id)
      this.channelInfo = res.data
      // console.log(JSON.stringify(this.channelInfo))
    },
    // 跳转到全部回复
    toAllReply(res) {
      if(!this.removing){
        uni.navigateTo({
          url: '/pages/comment/reply?id=' + res.id
        });
      }
    },
    // 点赞
    async getLike(index) {
      let token = getToken();
      if (!(token !== null && token !== '' && token !== undefined)) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateTo({url: '/pages/my/login'})
        }, 500)
        return;
      }
      const res = await likeComment(this.commentList[index].id)
      this.commentList[index].isLiked = !this.commentList[index].isLiked;
      if (this.commentList[index].isLiked) {
        this.commentList[index].liked++;
      } else {
        this.commentList[index].liked--;
      }
    },
    async collectPost() {
      let token = getToken();
      if (!(token !== null && token !== '' && token !== undefined)) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateTo({url: '/pages/my/login'})
        }, 500)
        return;
      }
      const res = await collectPost(this.postInfo.id)
      if (res.code == 200) {
        if (this.postInfo.isCollected) {
          uni.showToast({
            title: '取消收藏',
            icon: 'none',
            position: 'bottom'
          });
          this.bottomList2 = [
            {
              url: 'https://www.douluodalu.icu:9000/school/static/post_image.png',
              type: 1
            }, {
              url: 'https://www.douluodalu.icu:9000/school/static/post_collection.png',
              type: 6
            }
          ]
        } else {
          uni.showToast({
            title: '收藏成功',
            icon: 'none',
            position: 'bottom'
          });
          this.bottomList2 = [
            {
              url: 'https://www.douluodalu.icu:9000/school/static/post_image.png',
              type: 1
            }, {
              url: 'https://www.douluodalu.icu:9000/school/static/post_collection_active.png',
              type: 6
            }
          ]
        }
        this.postInfo.isCollected = !this.postInfo.isCollected;
      }
    },
    // 评论列表

  }
};
</script>

<style lang="scss" scoped>
.empty-comment {
  height: 40vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: rgb(192, 192, 192);
}

.like-image {
  height: 20px;
  width: 20px;
}

.comment {
  display: flex;
  padding: 30rpx;

  .left {
    .avatar {
      width: 64rpx;
      height: 64rpx;
      border-radius: 50%;
      background-color: #f2f2f2;
    }
  }

  .right {
    flex: 1;
    padding-left: 20rpx;
    font-size: 30rpx;

    .top {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10rpx;

      .name {
        color: #9a9a9a;
      }

      .like {
        display: flex;
        align-items: center;
        color: #9a9a9a;
        font-size: 26rpx;

        .num {
          margin-right: 4rpx;
          color: #9a9a9a;
        }
      }

      .highlight {
        color: #4ea4f9;

        .num {
          color: #4ea4f9;
        }
      }
    }

    .content {
      margin-bottom: 10rpx;
    }

    .reply-box {
      background-color: rgb(242, 242, 242);
      border-radius: 12rpx;
      padding: 0 20rpx;

      .item {
        display: flex;
        align-items: center;
        padding: 5rpx 0rpx;
        word-break: break-all;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        overflow: hidden;
        text-overflow: ellipsis;

        .username {
          font-size: 24rpx;
          color: #4ea4f9;
          display: flex;
          align-items: center;

          .owner {
            color: #4ea4f9;
            background-color: rgba(78, 164, 249, 0.19);
            padding: 1px 3px;
            border: none;
            border-radius: 3px
          }
        }
      }

      .all-reply {
        padding-bottom: 10rpx;
        display: flex;
        color: #4ea4f9;
        align-items: center;

        .more {
          margin-left: 6rpx;
        }
      }
    }

    .bottom {
      margin-top: 20rpx;
      display: flex;
      align-items: center;
      font-size: 24rpx;
      color: #9a9a9a;
      border-bottom: 1px solid #9e9e9e3d;
      padding-bottom: 10px;

      .reply {
        color: #9a9a9a;
        background-color: rgba(154, 154, 154, 0.14);
        border: none;
        padding: 2px 5px;
        border-radius: 5px;
        margin-left: 10rpx;
      }
    }
  }
}

.file-item-multi {
  //margin-bottom: 0.5rem;
  border-radius: 5px;
  width: 6.7rem;
  height: 6.7rem;
  position: relative;
}

.play-btn {
  width: 30px;
  height: 30px;
  top: 35%;
  left: 35%;
  position: absolute
}

#bottom-list {
  display: flex;
  flex-direction: column;
  padding: 10px 0;
  bottom: 0;
  z-index: 999;
  width: 100vw;
  position: fixed;
  background-color: #FFFFFF;
  //max-height: 12vh;
}

textarea {
  background-color: rgba(154, 154, 154, 0.15);
  border-radius: 60rpx;
  padding: 8px;
  max-height: 12vh;
}

.bottom-media-list {
  display: flex;
  align-items: center;
  margin: 0 30rpx;
  width: max-content;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  box-shadow: 0 0 10px 0px #b7b4b4;
}

.bottom-media-list-item {
  padding: 5px;
}

.bottom-media-list-item-image {
  width: 128rpx;
  height: 128rpx;
  z-index: 99
}

.close-images {
  z-index: 999;
  position: relative;
  left: 3.9rem;
  top: -5.0rem;
  background-color: white;
  border-radius: 50%;
  width: max-content;
  height: max-content;
}

.textarea-model-wrapper {
  display: flex;
  align-items: center;
  margin: 0 30rpx;

}

.media {
  padding: 0.2rem;
  width: 1.5rem;
  height: 1.5rem;
  margin: 0.5vw
}

.send-btn {
  color: #4ea4f9 !important;
  background-color: white !important;
  border: none !important;
  outline: none !important;
  border-radius: 0 !important;
  font-size: 14px !important;
  padding: 2px;
  margin: 0;
  letter-spacing: 5px;
  box-sizing: unset !important;
  opacity: 1 !important;
}

button[disabled] {
  box-sizing: unset !important;
  background-color: white !important; /* 禁用时的背景颜色 */
  color: rgba(78, 164, 249, 0.69) !important; /* 禁用时的文字颜色 */
}

button::after {
  border: none;
}

</style>
